<template>
  <el-dialog
      v-model="visible"
      :title="`${paramsProps.title}`"
      :destroy-on-close="true"
      draggable
  >
    <el-form
        ref="ruleFormRef"
        label-width="140px"
        label-suffix=" :"
        :rules="rules"
        :model="paramsProps.row"
        @submit.enter.prevent="handleSubmit"
    >
      <el-form-item label="字典名称" prop="describe">
        <el-input
            v-model="paramsProps.row.name"
            placeholder="请填写字典名字"
            clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="编码" prop="describe">
        <el-input
            v-model="paramsProps.row.code"
            placeholder="请填写字典编码"
            clearable
        ></el-input>
      </el-form-item>
    </el-form>

    <el-button type="primary" @click="addItem(paramsProps.row)" v-if="!paramsProps.isAdd">+ 新增</el-button>
    <el-table :data="paramsProps.row.details"  v-if="!paramsProps.isAdd" border>
      <el-table-column label="字典项编码">
        <template #default="{ row }">
          <el-input v-model="row.numKey" placeholder="请输入字典项编码"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="名称">
        <template #default="{ row }">
          <el-input v-model="row.name" placeholder="请输入字典名称"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="对应值">
        <template #default="{ row }">
          <el-input v-model="row.value" placeholder="请输入字典项对应"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作" :min-width="120">
        <template #default="{ row }">
<!--          <div style="display: flex; justify-content: flex-start; align-items: center; gap: 10px; width: 100%;">-->
<!--            <el-button type="text" @click="addSubItem(row)" style="color: red;">删除</el-button>-->
<!--            <el-button type="text" @click="disableItem(row)">开启/禁用</el-button>-->
<!--          </div>-->
          <el-button type="text" @click="deleteItem(row,paramsProps.row)" style="color: red;">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-row>
      <el-col :span="24" style="text-align: right;">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script setup lang="ts">
import {ref, reactive, type UnwrapRef} from 'vue'
import {type ElForm, ElMessage} from 'element-plus'
import {
  deleteNovelDictDetailApi,
  editNovelDictDetailApi, getNovelDictApi,
  getNovelDictDetailApi,
} from "@/api/modules/novel/novelDict";

defineOptions({
  name: 'NovelDictForm'
})

const rules = reactive({})

const visible = ref(false)
const paramsProps = ref<View.DefaultParams>({
  title: '',
  row: {},
  api: undefined,
  getTableList: undefined ,
  isAdd: undefined
})

// 接收父组件传过来的参数
const acceptParams = (params: View.DefaultParams) => {
  paramsProps.value = params
  visible.value = true
}

// 提交数据（新增/编辑）
const ruleFormRef = ref<InstanceType<typeof ElForm>>()


const handleSubmit = () => {
  ruleFormRef.value!.validate(async (valid) => {
    if (!valid) return

    if (paramsProps.value?.row?.details?.size !=0){
      if (!validData()){
        return
      }

      try {
        await editNovelDictDetailApi( paramsProps.value?.row);
        ElMessage.success({message: `${paramsProps.value.title}成功！`})
        reFreshDetail(paramsProps.value?.row?.id)
        paramsProps.value.getTableList!()
        // visible.value = false
      } catch (error) {
        console.log(error)
      }

      return
    }

    try {
      await paramsProps.value.api!(paramsProps.value.row)
      ElMessage.success({message: `${paramsProps.value.title}成功！`})
      paramsProps.value.getTableList!()
      // visible.value = false
    } catch (error) {
      console.log(error)
    }
  })
}

defineExpose({
  acceptParams
})


// 启用状态，1 表示启用，0 表示禁用
const enabledStatus = ref('1');

// 模拟静态数据字典项数据
const dictionaryItems = ref([]);

// 新增字典项方法
const addItem = (row: UnwrapRef<View.DefaultParams["row"]> | { [p: string]: any }) => {
  // 这里可以实现添加新字典项的逻辑，比如弹出表单让用户输入等
  row?.details.push({dictId : row.id ,tempId : (function() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
    })()});
  console.log('row',row);
};

// 添加下级方法
const deleteItem = (row :any, rows: UnwrapRef<View.DefaultParams["row"]> | { [p: string]: any }) => {
  try {
    if (!row.tempId){
      deleteNovelDictDetailApi({ids: [row.id]});
      rows.details = rows.details.filter((item: any) => item.id !== row.id);
    }else {
      rows.details = rows.details.filter((item: any) => item.tempId !== row.tempId);
    }
    if (paramsProps?.value) {
      paramsProps.value.row = rows;
    }
    ElMessage.success({message: `删除成功！`});
    if (!row.id){
      return
    }
    paramsProps.value.getTableList!()
    // visible.value = false
  } catch (error) {
    console.log(error)
  }

};

const reFreshDetail = async(id : any) => {
  try {
    // 使用 Promise.all 来并行获取 record 和 detailData
    const [recordTmp, detailData] = await Promise.all([
      getNovelDictApi({ id: id }),
      getNovelDictDetailApi({ id: id })
    ]);
    // 使用 detailData 更新 record.details
    debugger
    const record = recordTmp?.data
    if (record) {
      record.details = detailData?.data?.rows ?? [];
    }
    paramsProps.value.row = record;
    debugger
    console.log('paramsProps', paramsProps);

  } catch (error) {
    console.log(error);
  }

}

const validData = () => {
  const isNotEmpty = paramsProps.value?.row?.details?.some((item: any) => {
    return item.numKey != null && item.numKey !== ''
        && item.name != null && item.name !== ''
        && item.value != null && item.value !== '';
  });

  if (!isNotEmpty) {
    ElMessage.error({message: `字典中存在空值`})
    return false;
  }

  const numkeys = new Set();
  const hasDuplicate = paramsProps.value?.row?.details?.some((detail: any) => {
    if (numkeys.has(detail.numKey)) {
      return true; // 找到重复
    }
    numkeys.add(detail.numKey);
    return false;
  });

  if (hasDuplicate) {
    ElMessage.error({message: `字典项编码不可存在重复的值`})
    return false;
  }
  return true;
}
</script>

<style scoped lang="scss"></style>